<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加角色 -->
      <el-button type="primary" @click="add_dialogVisible = true"
        >添加角色</el-button
      >
      <!-- 角色列表区域 -->
      <el-table :data="roleList" border stripe>
        <!-- 展开行 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              class="vcenter"
              :class="['bdbottom', i1 === 0 ? 'bdtop' : '']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag
                  closable
                  @close="deletepermissionById(scope.row, item1.id)"
                  >{{ item1.authName }}</el-tag
                ><i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <el-row
                  class="vcenter"
                  :class="[i2 === 0 ? '' : 'bdtop']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <!-- 渲染二级权限 -->
                  <el-col :span="6">
                    <el-tag
                      closable
                      type="success"
                      @close="deletepermissionById(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    ><i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 渲染三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      closable
                      type="warning"
                      :class="[i3 === 0 ? '' : 'bdtop']"
                      v-for="(item3, i3) in item2.children"
                      :key="item3.id"
                      @close="deletepermissionById(scope.row, item3.id)"
                    >
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"> </el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 编辑 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="getRoleById(scope.row.id)"
            ></el-button>
            <!-- 删除 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteRoleById(scope.row.id)"
            ></el-button>
            <!-- 分配权限 -->
            <el-tooltip
              effect="dark"
              content="分配权限"
              placement="top"
              :enterable="false"
              ><el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="showPermission(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="add_dialogVisible"
      width="30%"
      @close="addRoleClosed"
    >
      <!-- 内容主体区 -->
      <el-form
        :model="addForm"
        :rules="addrules"
        ref="addruleRef"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="add_dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改角色对话框 -->
    <el-dialog
      title="修改角色"
      :visible.sync="update_dialogVisible"
      width="30%"
      @close="updateRoleClosed"
    >
      <!-- 内容主体区 -->
      <el-form
        :model="getRoleByIdForm"
        :rules="updateRules"
        ref="updateRulesRef"
        label-width="70px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="getRoleByIdForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="getRoleByIdForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="update_dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateRole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限的对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="show_dialogVisible"
      @click="showRoleClosed"
      width="30%"
    >
      <!-- 内容主体区 -->
      <el-tree
        :data="permissionList"
        :props="permissionProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defKeys"
        ref="treeRef"
      >
      </el-tree>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="show_dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotpermission">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      roleList: [],
      // 控制添加角色对话框的显示与隐藏
      add_dialogVisible: false,
      // 添加角色的表单数据
      addForm: {
        roleName: '',
        roleDesc: '',
      },
      // 添加角色的验证规则
      addrules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          {
            min: 1,
            max: 10,
            message: '至少1个字符',
            trigger: 'blur',
          },
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 1, max: 15, message: '至少1个字符', trigger: 'blur' },
        ],
      },
      // 控制修改角色对话框的显示与隐藏
      update_dialogVisible: false,
      // 根据id获取角色的表单数据
      getRoleByIdForm: {},
      // 编辑角色的验证规则
      updateRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          {
            min: 1,
            max: 10,
            message: '至少1个字符',
            trigger: 'blur',
          },
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 1, max: 15, message: '至少1个字符', trigger: 'blur' },
        ],
      },
      // 控制分配权限对话框的显示与隐藏
      show_dialogVisible: false,
      // 权限数据
      permissionList: [],
      // 树形控件的属性绑定对象
      permissionProps: {
        children: 'children',
        label: 'authName',
      },
      // 默认选中的权限节点
      defKeys: [],
      // 当前即将分配角色的id
      roleId: '',
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    //   获取角色列表
    async getRoleList() {
      const { data: res } = await this.$http.get('roles')
      // console.log(res);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success('获取角色列表成功')
      this.roleList = res.data
    },
    // 监听添加角色对话框的关闭
    addRoleClosed() {
      this.$refs.addruleRef.resetFields()
    },
    // 点击添加按钮,添加新角色
    addRole() {
      this.$refs.addruleRef.validate(async (data) => {
        // console.log(data);
        if (!data) return
        // 发起添加请求
        const { data: res } = await this.$http.post('roles', this.addForm)
        // console.log(res);
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success('添加角色成功')
        // 关闭添加角色对话框
        this.add_dialogVisible = false
        // 重新获取角色列表数据
        this.getRoleList()
      })
    },
    // 监听编辑角色对话框的关闭
    updateRoleClosed() {
      this.$refs.updateRulesRef.resetFields()
    },
    // 点击编辑按钮，获取角色信息
    async getRoleById(id) {
      // 根据 ID 查询角色信息
      const { data: res } = await this.$http.get('roles/' + id)
      //   console.log(res)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success('根据id获取角色成功')
      this.getRoleByIdForm = res.data
      // 显示对话框
      this.update_dialogVisible = true
    },
    // 提交编辑后角色的信息
    updateRole() {
      this.$refs.updateRulesRef.validate(async (data) => {
        if (!data) return
        // 发起修改后提交角色的请求
        const { data: res } = await this.$http.put(
          'roles/' + this.getRoleByIdForm.roleId,
          {
            roleName: this.getRoleByIdForm.roleName,
            roleDesc: this.getRoleByIdForm.roleDesc,
          }
        )
        // console.log(this.getRoleByIdForm)
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success('修改角色成功')
        // 关闭添加角色对话框
        this.update_dialogVisible = false
        // 重新获取角色列表数据
        this.getRoleList()
      })
    },
    // 根据id删除单个角色
    async deleteRoleById(id) {
      // 弹框询问是否删除数据
      const result = await this.$confirm(
        '此操作将永久删除该角色, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      // console.log(res);
      if (result !== 'confirm') return this.$message.info('已取消删除')
      const { data: res } = await this.$http.delete('roles/' + id)
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getRoleList()
    },
    // 根据id删除权限
    async deletepermissionById(role, id) {
      const result = await this.$confirm(
        '此操作将永久删除该角色, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      // console.log(res);
      if (result !== 'confirm') return this.$message.info('已取消删除')
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${id}`
      )
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success('删除权限成功')
      role.children = res.data
    },
    // 展示分配权限的对话框
    async showPermission(role) {
      this.roleId = role.id
      // 获取权限数据
      const { data: res } = await this.$http.get('rights/tree')
      // console.log(res);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success('获取权限数据成功')
      // 把获取的权限数据保存data中
      this.permissionList = res.data
      //获取三级节点
      this.getDefKeys(role, this.defKeys)
      // 显示对话框
      this.show_dialogVisible = true
    },
    // 获取角色下三级权限的id,保存到defKeys
    getDefKeys(node, arr) {
      // 不包含children则是三级
      if (!node.children) return arr.push(node.id)
      node.children.forEach((item) => {
        this.getDefKeys(item, arr)
      })
    },
    // 监听分配权限对话框的关闭
    showRoleClosed() {
      this.$refs.updateRulesRef.resetFields()
    },
    // 提交修改后的分配权限
    async allotpermission() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ]
      const idStr = keys.join(',')
      console.log(idStr)
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: idStr }
      )
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success('分配权限成功')
      this.getRoleList()
      this.show_dialogVisible = false
    },
  },
}
</script>
<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>